package com.x.epspace.service;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.servlet.ModelAndView;

import com.weixin.publicnumber.api.SnsAPI;
import com.weixin.publicnumber.bean.SnsToken;
import com.x.epspace.common.AppConfig;
import com.x.epspace.common.SHA1;
import com.x.epspace.common.StringTools;
import com.x.epspace.common.Tool;
import com.x.epspace.dao.RegUserDao;
import com.x.epspace.entity.RegUser;
import com.x.epspace.ext.HandleSessionService;
import com.x.epspace.message.client.MessageSender;

@Service("regService")
public class RegService {

	private static final Log log = LogFactory.getLog(RegService.class);

	@Resource
	private MessageSender messageSender;

	@Resource
	private RegUserDao regUserDao;
	
	@Resource
	private HandleSessionService handleSession;
	
	public long getReguserCount(){
		return regUserDao.count();
	}
	
	/**
	 * 发送短信验证码
	 * @param mobile 手机号
	 * @return
	 */
	public Map<String, String> sendValidSms(String mobile,String checkcode) {
		//初始化返回
		Map<String, String> returnMap = new HashMap<String, String>();
		//手机号不能为空
		if (!Tool.isNotNullOrEmpty(mobile)) {
			returnMap.put("result",
					AppConfig.getProperty("fail", "return_code"));
			returnMap.put("description", "手机号不能为空");
			return returnMap;
		}
		
		if (!Tool.isNotNullOrEmpty(checkcode)) {
			returnMap.put("result",
					AppConfig.getProperty("fail", "return_code"));
			returnMap.put("description", "图片验证码不能为空");
			return returnMap;
		}
		
		Object sessionCodeObj = handleSession.getVal("checkcode");
		if(sessionCodeObj==null || !checkcode.equals(sessionCodeObj.toString())){
			returnMap.put("result",
					AppConfig.getProperty("fail", "return_code"));
			returnMap.put("description", "图片验证码输入不正确");
			handleSession.setVal("checkcode", "");
			return returnMap;
		}
		handleSession.removeVal("checkcode");
		String validCode = Tool.getRandomSixNum();
		//发送短信验证码
		returnMap = messageSender.sendMessage(mobile, "注册验证码为" + validCode);
		if (returnMap.get("result").equals(
				AppConfig.getProperty("success", "return_code"))) {
			//发送成功
			//将验证码相关信息置入session
			Map<String,String> validcodeMap = new HashMap<String,String>(3);
			validcodeMap.put("mobile", mobile);
			validcodeMap.put("validcode", validCode);
			long expiretime = System.currentTimeMillis() + Long.parseLong(AppConfig.getProperty("smscode_expire_time", "system"));
			validcodeMap.put("expiretime", Long.toString(expiretime));
			
			//保存到session
			handleSession.setVal(AppConfig.getProperty("SMSCODE_SESSION_KEY", "SESSION_KEY"),
					validcodeMap);
						
			return returnMap;
		}
		//发送失败返回
		return returnMap;
	}

	/**
	 * 验证短信验证码
	 * @param mobile     手机号
	 * @param userInput  用户输入验证码
	 * @return
	 */
	public Map<String, String> validateSmscode(String mobile,String userInput,String checkcode) {
		//初始化返回
		Map<String, String> returnMap = new HashMap<String, String>();
		
		if (!Tool.isNotNullOrEmpty(userInput)){
			returnMap.put("result",
					AppConfig.getProperty("fail", "return_code"));
			returnMap.put("description", "输入验证码不能为空");
			return returnMap;
		}
		
//		if (!Tool.isNotNullOrEmpty(checkcode)){
//			returnMap.put("result",
//					AppConfig.getProperty("fail", "return_code"));
//			returnMap.put("description", "图片验证码不能为空");
//			return returnMap;
//		}
//
//		Object sessionCodeObj = handleSession.getVal("checkcode");
//		if(sessionCodeObj==null || !checkcode.equals(sessionCodeObj.toString())){
//			returnMap.put("result",
//					AppConfig.getProperty("fail", "return_code"));
//			returnMap.put("description", "图片验证码输入不正确");
//			return returnMap;
//		}
		
		
		//从session获取smscode
		Object codeObj = handleSession.getVal(AppConfig.getProperty("SMSCODE_SESSION_KEY", "SESSION_KEY"));
		
		if (codeObj == null){
			returnMap.put("result",
					AppConfig.getProperty("fail", "return_code"));
			returnMap.put("description", "短信验证码获取失败");
			return returnMap;
		}
		
		Map<String,String> syscodeMap = (Map<String,String>) codeObj;
		//判断验证码是否过期
		long expiretime = Long.parseLong(syscodeMap.get("expiretime"));
		if(expiretime < System.currentTimeMillis()){
			//验证码过期
			returnMap.put("result",
					AppConfig.getProperty("fail", "return_code"));
			returnMap.put("description", "短信验证码已过期");
			return returnMap;
		}
		
		//判断是否同一手机号
		if(!mobile.equals(syscodeMap.get("mobile"))){
			returnMap.put("result",
					AppConfig.getProperty("fail", "return_code"));
			returnMap.put("description", "手机号不正确");
			return returnMap;
		}
		
		//验证短信验证码
		if(!userInput.equals(syscodeMap.get("validcode"))){
			returnMap.put("result",
					AppConfig.getProperty("fail", "return_code"));
			returnMap.put("description", "验证码不正确");
			return returnMap;
		}
		
		handleSession.removeVal(AppConfig.getProperty("SMSCODE_SESSION_KEY", "SESSION_KEY"));
		
		returnMap.put("result",
				AppConfig.getProperty("success", "return_code"));
		returnMap.put("description", "验证码验证正确");
		return returnMap;
	}

	/**
	 * 注册用户
	 * @param mobile  手机号
	 * @param pwd     密码
	 * @return
	 */
	public Map<String,String> regUser(String mobile, String pwd,String wxuserid) {
		
		//初始化返回
		Map<String, String> returnMap = new HashMap<String, String>();
		if (!Tool.isNotNullOrEmpty(mobile)
				|| !Tool.isNotNullOrEmpty(pwd)){
			returnMap.put("result",
					AppConfig.getProperty("fail", "return_code"));
			returnMap.put("description", "参数不能为空");
			return returnMap;
		}
		//判断手机号是否已注册
		long count = regUserDao.count("mobile", mobile);
		if (count > 0){
			returnMap.put("result",
					AppConfig.getProperty("fail", "return_code"));
			returnMap.put("description", "该手机号已注册");
			return returnMap;
		}
		
				
		RegUser regUser = new RegUser();
		regUser.setMobile(mobile);
		regUser.setPwd(SHA1.toSHA1(mobile + pwd));
		regUser.setRegTime(System.currentTimeMillis());
		regUser.setStatus(AppConfig.getProperty("status_normal", "status_code"));
		regUser.setWxuserid(wxuserid);
		try {
			regUserDao.save(regUser);
			RegUser regUserSession = regUserDao.findOne("mobile", mobile);
			handleSession.setVal(AppConfig.getProperty("USER_SESSION_KEY", "SESSION_KEY"),
					       regUserSession);
			
		} catch (Exception e) {
			log.error(e);
			returnMap.put("result",
					AppConfig.getProperty("fail", "return_code"));
			returnMap.put("description", "注册用户失败");
			return returnMap;
		}
		returnMap.put("result",
				AppConfig.getProperty("success", "return_code"));
		returnMap.put("description", "注册用户成功");
		return returnMap;
	}
	
	/**
	 * 忘记密码后的重置密码
	 * @param mobile   手机号
	 * @param newpwd   新密码
	 * @return
	 */
	public Map<String,String> resetPwd(String mobile, String newpwd) {
		//初始化返回
		Map<String, String> returnMap = new HashMap<String, String>();
		
		RegUser regUser = regUserDao.findOne("mobile", mobile);
		if(regUser == null){
			returnMap.put("result",
					AppConfig.getProperty("fail", "return_code"));
			returnMap.put("description", "该手机号错误");
			return returnMap;
		}
		regUser.setPwd(SHA1.toSHA1(mobile + newpwd));
		try {
			regUserDao.save(regUser);
		} catch (Exception e) {
			log.error(e);
			returnMap.put("result",
					AppConfig.getProperty("fail", "return_code"));
			returnMap.put("description", "重置密码失败");
			return returnMap;
		}
		returnMap.put("result",
				AppConfig.getProperty("success", "return_code"));
		returnMap.put("description", "重置密码成功");
		return returnMap;
		
	}
	
	/**
	 * 修改密码
	 * @param mobile   手机号
	 * @param oldpwd   原密码
	 * @param newpwd   新密码
	 * @return
	 */
	public Map<String,String> modifyPwd(String mobile,String oldpwd,String newpwd) {
		//初始化返回
		Map<String, String> returnMap = new HashMap<String, String>();
				
		RegUser regUser = regUserDao.findOne("mobile", mobile);
		if(regUser == null){
			returnMap.put("result",
					AppConfig.getProperty("fail", "return_code"));
			returnMap.put("description", "该手机号错误");
			return returnMap;
		}
		//校验老密码
		if(!regUser.getPwd().equals(SHA1.toSHA1(mobile + oldpwd))){
			returnMap.put("result",
					AppConfig.getProperty("fail", "return_code"));
			returnMap.put("description", "原密码验证不正确");
			return returnMap;
		}
		
		//修改密码
		regUser.setPwd(SHA1.toSHA1(mobile + newpwd));
		try {
			regUserDao.save(regUser);
		} catch (Exception e) {
			log.error(e);
			returnMap.put("result",
					AppConfig.getProperty("fail", "return_code"));
			returnMap.put("description", "修改密码失败");
			return returnMap;
		}
		returnMap.put("result",
				AppConfig.getProperty("success", "return_code"));
		returnMap.put("description", "修改密码成功");
		return returnMap;
	}
	
	/**
	 * 用户登录
	 * @param mobile 手机号
	 * @param pwd    密码
	 * @return
	 */
	public Map<String,String> login(String mobile,String pwd,String wxuserid){
		//初始化返回
		Map<String, String> returnMap = new HashMap<String, String>();
		if(!Tool.isNotNullOrEmpty(mobile) || !Tool.isNotNullOrEmpty(pwd)){
			returnMap.put("result",
					AppConfig.getProperty("fail", "return_code"));
			returnMap.put("description", "手机号或密码不能为空");
			return returnMap;
		}
		
		RegUser regUser = regUserDao.findOne("mobile", mobile);
		if(regUser == null){
			returnMap.put("result",
					AppConfig.getProperty("fail", "return_code"));
			returnMap.put("description", "手机号或密码错误");
			return returnMap;
		}
		
		//校验密码
		if(!regUser.getPwd().equals(SHA1.toSHA1(mobile + pwd))){
			returnMap.put("result",
							AppConfig.getProperty("fail", "return_code"));
			returnMap.put("description", "手机号或密码错误");
			return returnMap;
		}
		
		//校验成功
		//处理用户微信号绑定
		if(StringTools.notNull(wxuserid)){
			regUser.setWxuserid(wxuserid);
			regUserDao.save(regUser);
		}
		handleSession.setVal(AppConfig.getProperty("USER_SESSION_KEY", "SESSION_KEY"),
				regUser);
		returnMap.put("result",
				AppConfig.getProperty("success", "return_code"));
		returnMap.put("description", "验证成功");
		return returnMap;
	}
	
	/**
	 * 注销
	 */
	public void logout(){
		handleSession.removeVal(AppConfig.getProperty("USER_SESSION_KEY", "SESSION_KEY"));
		handleSession.removeVal(AppConfig.getProperty("ENT_SESSION_KEY", "SESSION_KEY"));
	}
	
	/**
	 * 根据微信号提取用户信息
	 * @param wxuserid
	 * @return
	 */
	public RegUser getRegUserByWxuserid(String wxuserid){
		RegUser regUser = regUserDao.findOne("wxuserid", wxuserid);
		return regUser;
	}
	
	/**
	 * 绑定用户微信id
	 * @param mobile
	 * @param wxuserid
	 */
	public void bindRegWxuserid(String mobile,String wxuserid){
		RegUser regUser = regUserDao.findOne("mobile", mobile);
		if(regUser == null) return;
		regUser.setWxuserid(wxuserid);
		try {
			regUserDao.save(regUser);
		} catch (Exception e) {
			log.error(e);
		}
	}
	
	/**
	 * 处理微信登录
	 * @param mv
	 */
	public boolean handleWxLogin(ModelAndView mv,String code){
		String appid = AppConfig.getProperty("APPID", "Weixin_Config");
		String secret = AppConfig.getProperty("APPSECRET", "Weixin_Config");
		SnsAPI snsAPI = new SnsAPI();
		SnsToken snsToken = snsAPI.oauth2AccessToken(appid,secret,code);
		String wxuserid = snsToken.getOpenid();
		if(!StringTools.notNull(wxuserid)){
			mv.addObject("wxuserid", "");
			return false;
		}
		//wxuserid获取成功，提取用户信息
		RegUser regUser = getRegUserByWxuserid(wxuserid);
		if(regUser == null){
			//未绑定微信号或未注册
			mv.addObject("wxuserid", wxuserid);
			return false;
		}
		handleSession.setVal(AppConfig.getProperty("USER_SESSION_KEY", "SESSION_KEY"),
				regUser);
		mv.addObject("wxuserid", wxuserid);
		return true;
	}

}
